package drds.common.db.xml_mapping.script.defaults;

import drds.common.db.xml_mapping.builder.SqlSourceBuilder;
import drds.common.db.xml_mapping.mapping.BindSql;
import drds.common.db.xml_mapping.mapping.SqlSource;
import drds.common.db.xml_mapping.script.xml_tags.DynamicNode;
import drds.common.db.xml_mapping.script.xml_tags.DynamicNodeContext;
import drds.common.db.xml_mapping.session.Configuration;

import java.util.HashMap;


public class RawSqlSource implements SqlSource {

  private final SqlSource sqlSource;

  public RawSqlSource(Configuration configuration, DynamicNode rootNode, Class<?> parameterType) {
    this(configuration, getSql(configuration, rootNode), parameterType);
  }

  public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
    Class<?> clazz = parameterType == null ? Object.class : parameterType;
    sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
  }

  private static String getSql(Configuration configuration, DynamicNode rootNode) {
    DynamicNodeContext context = new DynamicNodeContext(configuration, null);
    rootNode.apply(context);
    return context.getSql();
  }

  @Override
  public BindSql getBoundSql(Object parameterObject) {
    return sqlSource.getBoundSql(parameterObject);
  }

}
